package com.company.common.Interceptor;

import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
public class LoginHandlerInterceptor implements HandlerInterceptor {

    //    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public boolean preHandle(@RequestBody HttpServletRequest request, @RequestBody HttpServletResponse response, @RequestBody Object handler) throws Exception {

        //        //获取请求头中的token
        //        String token = request.getHeader("token");
        //        if (StringUtils.isBlank(token)) {
        //            printJson(response, "");
        //            return false;
        //        }
        //        //校验token是否过期
        //        Object userObj = RedisUtil.get(token);
        //        if (userObj == null) {
        //            printJson(response, "");
        //            return false;
        //        }
        //        //将user数据保存到ThreadLocal中
        //        UserThreadLocal.set(token);
        //
        //
        //        //更新token
        //        RedisUtil.expire(token,3*60*60);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Requested-With, token");
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS, POST, PUT, DELETE");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Max-Age", "3600");
    }

    private static void printJson(HttpServletResponse response, String code) {
        Map<String, String> map = new HashMap<>();
        map.put("errorCode", "10086");
        map.put("message", "token失效,请重新登录");
        String content = JSON.toJSONString(map);
        printContent(response, content);
    }

    private static void printContent(HttpServletResponse response, String content) {
        try {
            response.reset();
            response.setContentType("application/json");
            response.setHeader("Cache-Control", "no-store");
            response.setCharacterEncoding("UTF-8");
            PrintWriter pw = response.getWriter();
            pw.write(content);
            pw.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
